/**
 * 天气工具类
 * 提供天气和位置相关的API封装
 */

// 天气API配置（可以根据实际情况修改）
const WEATHER_CONFIG = {
  // OpenWeatherMap API Key（需要注册获取）
  openWeatherApiKey: 'YOUR_API_KEY',
  
  // 和风天气API Key（备选方案）
  heWeatherApiKey: 'YOUR_API_KEY',
  
  // 默认城市（定位失败时使用）
  defaultCity: {
    name: '北京',
    lat: 39.9042,
    lon: 116.4074
  }
}

/**
 * 获取位置信息
 */
export const getLocation = () => {
  return new Promise((resolve, reject) => {
    if (!navigator.geolocation) {
      reject(new Error('浏览器不支持地理位置定位'))
      return
    }

    navigator.geolocation.getCurrentPosition(
      (position) => {
        resolve({
          latitude: position.coords.latitude,
          longitude: position.coords.longitude,
          accuracy: position.coords.accuracy
        })
      },
      (error) => {
        reject(error)
      },
      {
        enableHighAccuracy: false,
        timeout: 5000,
        maximumAge: 300000 // 5分钟缓存
      }
    )
  })
}

/**
 * 通过坐标获取城市信息
 */
export const getCityByCoordinates = async (lat, lon) => {
  try {
    // 使用免费API获取城市信息
    const response = await fetch(
      `https://api.bigdatacloud.net/data/reverse-geocode-client?latitude=${lat}&longitude=${lon}&localityLanguage=zh`
    )
    const data = await response.json()
    
    return {
      city: data.locality || data.city || '未知',
      province: data.principalSubdivision || '',
      district: data.localityInfo?.administrative?.[0]?.name || '',
      country: data.countryName || ''
    }
  } catch (error) {
    console.error('获取城市信息失败:', error)
    throw error
  }
}

/**
 * 获取天气信息（OpenWeatherMap）
 */
export const getWeatherByCoordinates = async (lat, lon, apiKey = null) => {
  const key = apiKey || WEATHER_CONFIG.openWeatherApiKey
  
  if (key === 'YOUR_API_KEY') {
    // 如果未配置API Key，返回模拟数据
    return {
      temp: 22,
      desc: '晴朗',
      icon: 'sunny',
      humidity: 60,
      windSpeed: 5
    }
  }
  
  try {
    const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${key}&units=metric&lang=zh_cn`
    const response = await fetch(url)
    const data = await response.json()
    
    if (data.cod === 200) {
      return {
        temp: Math.round(data.main.temp),
        desc: data.weather[0]?.description || '未知',
        icon: getWeatherIcon(data.weather[0]?.main),
        humidity: data.main.humidity,
        windSpeed: data.wind?.speed || 0,
        pressure: data.main.pressure
      }
    } else {
      throw new Error(data.message || '获取天气失败')
    }
  } catch (error) {
    console.error('获取天气失败:', error)
    throw error
  }
}

/**
 * 根据天气代码获取图标类型
 */
const getWeatherIcon = (weatherMain) => {
  const iconMap = {
    'Clear': 'sunny',
    'Clouds': 'cloudy',
    'Rain': 'cloudy',
    'Drizzle': 'cloudy',
    'Thunderstorm': 'cloudy',
    'Snow': 'cloudy',
    'Mist': 'cloudy',
    'Fog': 'cloudy',
    'Haze': 'cloudy'
  }
  return iconMap[weatherMain] || 'sunny'
}

/**
 * 获取默认位置和天气
 */
export const getDefaultWeather = async () => {
  const { lat, lon } = WEATHER_CONFIG.defaultCity
  const cityInfo = await getCityByCoordinates(lat, lon)
  const weatherInfo = await getWeatherByCoordinates(lat, lon)
  
  return {
    location: {
      city: cityInfo.city || WEATHER_CONFIG.defaultCity.name,
      province: cityInfo.province || '',
      district: cityInfo.district || ''
    },
    weather: weatherInfo
  }
}

export default {
  getLocation,
  getCityByCoordinates,
  getWeatherByCoordinates,
  getDefaultWeather
}

